package com.wisnews.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wisnews.pojo.sr.entity.Member;
import com.wisnews.service.sr.IMemberService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description：
 * @Author: yuyd
 * @Email: yyd8358@foxmail.com
 * @Date: 2021/2/4 14:47
 * @Version 1.0
 */
public class MemberRealm extends AuthorizingRealm {

    private static final transient Logger log = LoggerFactory.getLogger(AuthorizingRealm.class);

    @Autowired
    private IMemberService memberService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * @description: 会员认证
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/2/26 17:30
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        log.error("====> 执行了前台用户认证！");
        //获取用户输入的信息
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;

        LambdaQueryWrapper<Member> lambdaQuery = Wrappers.lambdaQuery();

        //根据用户名查询
        Member member = memberService.getOne(
                lambdaQuery.eq(StringUtils.isNotBlank(token.getUsername()), Member::getUserLoginCode, token.getUsername()));
        if (ObjectUtils.isNull(member)){
            lambdaQuery.clear();
            member = memberService.getOne(lambdaQuery.eq(StringUtils.isNotBlank(token.getUsername()), Member::getUserEmail, token.getUsername()));

            if (ObjectUtils.isNull(member)){
                throw new UnknownAccountException("用户名不存在");
            }
        }

        //返回执行认证
        return new SimpleAuthenticationInfo(member, member.getUserPasswd(),getName());
    }
}
